package com.app.teaware.goods;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BaseListBean;
import com.app.teaware.bean.BasisBean;
import com.app.teaware.bean.CompanyListBean;
import com.app.teaware.bean.CompanyListData;
import com.app.teaware.bean.CraftListBean;
import com.app.teaware.bean.CraftListData;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.MenuBean;
import com.app.teaware.bean.WorkListBean;
import com.app.teaware.bean.WorkListData;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.OnClickUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.ActivityTool;
import my.TimeUtils;
import my.ViewUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 领料管理-退料管理-加工入库
 */
public class GoodsListActivity extends BasisActivity {

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private WorkListBean mListBean;


    @BindView(R.id.text_start_time)
    TextView textStartTime;
    @BindView(R.id.text_end_time)
    TextView textEndTime;
    Calendar calendarStart;
    Calendar calendarEnd;

    @BindView(R.id.spinner_type)
    MaterialSpinner spinner_type;
    private String text_spinner_type;
    @BindView(R.id.spinner_custom)
    MaterialSpinner spinner_custom;
    private CompanyListData curCompany;
    @BindView(R.id.spinner_craft)
    MaterialSpinner spinner_craft;
    private CraftListData curCraft;
    @BindView(R.id.spinner_status)
    MaterialSpinner spinner_status;
    private String text_spinner_status;

    private CompanyListBean companyList;


    @Override
    public void initViews() {
        setContentView(R.layout.goods_list_activity);
        setTitle(""+ MyUtils.getHomeSelectName());
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(true);

        setTitleRightButton(R.drawable.icon_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle extras = new Bundle();
                extras.putString("title","新增");
                ActivityTool.skipActivityForResult(mContext, AddOrEditGoodsActivity.class,extras,WARNLISTRESULT);
            }
        });
        initCalendar();
        initSpiner();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new WorkListBean();
        setListView();
        setTitleLeftButton(null);
        getList();
    }

    private void  initCalendar(){
        calendarStart = Calendar.getInstance();
        calendarStart.add(Calendar.MONTH, 0);
        calendarStart.set(Calendar.DAY_OF_MONTH, 1);
        calendarEnd = Calendar.getInstance();
        calendarEnd.set(Calendar.HOUR_OF_DAY,0);
        calendarEnd.set(Calendar.MINUTE,0);
        calendarEnd.set(Calendar.SECOND,0);
        calendarEnd.set(Calendar.MILLISECOND,0);
        textStartTime.setText(calendarStart == null? "": TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
    }

    private void  initSpiner(){
        switch (MyUtils.getHomeSelectName()) {
            case "加工入库":
                spinner_type.setItems(getResources().getStringArray(R.array.order_type));
                break;
            default:
                spinner_type.setItems(getResources().getStringArray(R.array.good_type_and_show));
                break;
        };


        spinner_type.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                text_spinner_type = item;
                getList();
            }
        });


        spinner_status.setItems(getResources().getStringArray(R.array.good_status_and_show));
        spinner_status.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                text_spinner_status = item;
                getList();
            }
        });


        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
        MyHttpUtils.get(Constants.URL_CRAFT_SELECT_ALL, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        CraftListBean basicBean = (CraftListBean) result;
                        if(basicBean.getAllNames()!=null){
                            CraftListBean craftList = new CraftListBean();
                            craftList.initCraftBean();
                            craftList.getList().addAll(basicBean.getList());
                            spinner_craft.setItems(craftList.getAllNameList());
                            spinner_craft.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
                                @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                                    curCraft = craftList.getList().get(position);
                                    getList();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);

                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        hideLoading();
                    }
                },
                0, CraftListBean.class);

        if(MyUtils.getHomeSelectName().equals("加工入库")){
            getCompanyList("1");
            spinner_custom.setVisibility(View.VISIBLE);
        }else {
            spinner_custom.setVisibility(View.GONE);
        }

    }

    private void getCompanyList(String cfsign) {

        MenuBean menuBean = LoginBean.getInstance().getMenuBeanByMna(MyUtils.getHomeSelectName());
        if(menuBean == null)return;
        MyParams params = new MyParams();
        params.put("aid",menuBean.getAid() );
        params.put("cfsign", cfsign);

        MyHttpUtils.get(Constants.URL_COMPANY_SELECT_ALL, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        CompanyListBean basicBean = (CompanyListBean) result;
                        if(basicBean != null && basicBean.getList().size()>0){
                            CompanyListBean companyList = new CompanyListBean();
                            companyList.initCustom();
                            companyList.getList().addAll(basicBean.getList());
                            spinner_custom.setItems(companyList.getAllCompanyNameList());
                            spinner_custom.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
                                @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
//                                    showToast("Clicked " + item +"position " + position );
                                    curCompany = companyList.getList().get(position);
                                    getList();
                                }
                            });
                        }

                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);

                    }

                    @Override
                    public void onFinish(int httpWhat) {

                    }
                },
                0, CompanyListBean.class);

    }


    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
//        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }



    private void getList() {

        MenuBean menuBean = LoginBean.getInstance().getMenuBeanByMna(MyUtils.getHomeSelectName());
        if(menuBean == null)return;

        MyParams params = new MyParams();
        showProgress();
        params.put("aid",menuBean.getAid() );
        params.put("bfs", MyUtils.getHomeSelectId());
        params.put("id", menuBean.getId());
        if(!TextUtils.isEmpty(text_spinner_status) && !text_spinner_status.equals("状态")){
            params.put("tys", text_spinner_status);            //状态
        }
        if(!TextUtils.isEmpty(text_spinner_type) && !text_spinner_type.equals("类型")){
            params.put("mty", text_spinner_type);            //类型
        }
        if(curCraft != null && !curCraft.getCna().equals("工艺")){
            params.put("cid", curCraft.getCid());            //工艺id
        }
        if(curCompany != null && !curCompany.getCna().equals("客户")){
            params.put("mna", curCompany.getCna());            //客户名称
        }
        params.put("bstime", textStartTime.getText().toString().trim());
        params.put("betime", textEndTime.getText().toString().trim());
        params.put(BaseListBean.PAGE_NAME, mListBean.getNextPage());
        params.put(BaseListBean.PAGE_SIZE_NAME, BaseListBean.PAGE_SIZE);

        MyHttpUtils.get(Constants.URL_WORK_SELECT_PAGE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        BasisBean basisBean = (BasisBean) result;
                        Gson gson = new Gson();
                        WorkListBean bean  = gson.fromJson(basisBean.getResultData(), WorkListBean.class);
                        mListBean.addListBean(bean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                        onListViewComplete();
                    }
                },
                0, BasisBean.class);

    }


    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.goods_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.view_wno)
            public View view_wno;
            @BindView(R.id.text_time)
            public TextView text_time;
            @BindView(R.id.text_no)
            public TextView text_no;
            @BindView(R.id.text_wno)        //单号
            public TextView text_wno;
            @BindView(R.id.text_maker)
            public TextView text_maker;
            @BindView(R.id.view_craft)
            public View view_craft;
            @BindView(R.id.text_craft)
            public TextView text_craft;
            @BindView(R.id.btn_delete)
            public TextView btn_delete;
            @BindView(R.id.btn_examine)
            public TextView btn_examine;
            @BindView(R.id.btn_edit)
            public TextView btn_edit;
            @BindView(R.id.text_type)
            public TextView text_type;
            @BindView(R.id.img_status_tag)
            public ImageView img_status_tag;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
//                img_icon.setVisibility(View.VISIBLE);
            }

            public void bind(int position) {
                WorkListData data = mListBean.getList().get(position);
//                img_icon.setImageResource(R.drawable.icon_doc);
                text_type.setText(""+data.getMty());
                switch (data.getMty()){
                    case "生产":
                        text_wno.setText(""+data.getWno());
                        view_wno.setVisibility(View.VISIBLE);
                        break;
                    default:
                        view_wno.setVisibility(View.GONE);
                        break;
                }
                if(TextUtils.isEmpty(data.getCna())){
                    view_craft.setVisibility(View.GONE);
                }else {
                    text_craft.setText(""+data.getCna());
                    view_craft.setVisibility(View.VISIBLE);
                }


                text_no.setText(""+data.getMno());   //领料单号
                text_time.setText(""+data.getMdt());
                text_maker.setText(""+data.getUno());
                btn_examine.setText(data.getTys());
                img_status_tag.setImageResource(data.getImaByTys());
                btn_delete.setTag(position);
                btn_examine.setTag(position);
                btn_edit.setTag(position);
                list_item.setTag(position);

            }
            @OnClick(R.id.btn_delete)
            void onItemDelClick(View view){
                if (!OnClickUtils.isFastClick()) {
                    // 进行点   击事件后的逻辑操作
                    int position = (int) view.getTag();
                    WorkListData data = mListBean.getList().get(position);
                    MenuBean menuBean = LoginBean.getInstance().getMenuBeanByMna(MyUtils.getHomeSelectName());
                    if(menuBean == null)return;
                    MyParams params = new MyParams();
                    showProgress();
                    params.put("aid",menuBean.getAid() );
                    params.put("bfs", MyUtils.getHomeSelectId());
                    params.put("id", menuBean.getId());
                    params.put("mid", data.getMid());
                    MyHttpUtils.delete(Constants.URL_WORK_DELETE_BY_ID, params, new MyHttpListener() {
                                @Override
                                public void onSuccess(int httpWhat, Object result) {
                                    if (isFinishing()) return;
                                    BasisBean basisBean = (BasisBean) result;
                                    showToast(basisBean.getStatusInfo());
                                    mListBean.getList().remove(position);
                                    setListView();
                                }

                                @Override
                                public void onFailure(int httpWhat, Object result) {
                                    super.onFailure(httpWhat, result);
                                    setListView();
                                }

                                @Override
                                public void onFinish(int httpWhat) {
                                    dismissProgress();
                                    onListViewComplete();
                                }
                            },
                            0, BasisBean.class);
                }
            }

            @OnClick(R.id.btn_examine)
            void onItemExaClick(View view){
                if (!OnClickUtils.isFastClick()) {
                    // 进行点   击事件后的逻辑操作
                    int position = (int) view.getTag();
                    WorkListData data = mListBean.getList().get(position);
                    MenuBean menuBean = LoginBean.getInstance().getMenuBeanByMna(MyUtils.getHomeSelectName());
                    if(menuBean == null)return;
                    MyParams params = new MyParams();
                    showProgress();
                    switch (data.getTys()){
                        case "未审核":
                            params.put("adt",TimeUtils.getCurrentTimeByFormat("yyyy-MM-dd"));
                            params.put("aid",menuBean.getAid());
                            params.put("id", menuBean.getId());
                            params.put("tid",data.getMid());
                            params.put("una", LoginBean.getInstance().getUname());
                            params.put("uno", LoginBean.getInstance().getUno());
                            MyHttpUtils.post(Constants.URL_AUDITUSERS_INSERT, params, new MyHttpListener() {
                                        @Override
                                        public void onSuccess(int httpWhat, Object result) {
                                            if (isFinishing()) return;
                                            BasisBean basisBean = (BasisBean) result;
                                            showToast(basisBean.getStatusInfo());
                                            data.setTys("已审核");
                                            mRecyclerView.notifyItemChanged(position);
                                        }

                                        @Override
                                        public void onFailure(int httpWhat, Object result) {
                                            super.onFailure(httpWhat, result);
                                        }

                                        @Override
                                        public void onFinish(int httpWhat) {
                                            dismissProgress();
                                        }
                                    },
                                    0, BasisBean.class);
                            break;
                        case "已审核":
                            params.put("tid",data.getMid());
                            params.put("aid",menuBean.getAid());
                            params.put("mid", menuBean.getId());
                            params.put("uno", LoginBean.getInstance().getUno());
                            MyHttpUtils.delete(Constants.URL_AUDITUSERS_DELETE_BY_ID, params, new MyHttpListener() {
                                        @Override
                                        public void onSuccess(int httpWhat, Object result) {
                                            if (isFinishing()) return;
                                            BasisBean basisBean = (BasisBean) result;
                                            showToast(basisBean.getStatusInfo());
                                            data.setTys("未审核");
                                            mRecyclerView.notifyItemChanged(position);
                                        }

                                        @Override
                                        public void onFailure(int httpWhat, Object result) {
                                            super.onFailure(httpWhat, result);
                                        }

                                        @Override
                                        public void onFinish(int httpWhat) {
                                            dismissProgress();
                                        }
                                    },
                                    0, BasisBean.class);
                            break;
                    }
                }
            }

            @OnClick(R.id.btn_edit)
            void onItemEditClick(View view){
                if (!OnClickUtils.isFastClick()) {
                    // 进行点   击事件后的逻辑操作
                    int position = (int) view.getTag();
                    WorkListData data = mListBean.getList().get(position);
                    Bundle extras = new Bundle();
                    extras.putSerializable("bean",data);
                    extras.putString("title","修改");
                    ActivityTool.skipActivityForResult(mContext, AddOrEditGoodsActivity.class,extras,WARNLISTRESULT);

                }
            }


        }
    }

    public final static int WARNLISTRESULT = 44;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == WARNLISTRESULT){
            mListBean.refresh();
            getList();
        }
    }

    @OnClick(R.id.view_filter_1)
    void timeBeginChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarStart == null) {
                    calendarStart = Calendar.getInstance();
                }
                calendarStart.setTime(date);
                onTimeBeginChoosed();
            }
        })
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }


    void onTimeBeginChoosed() {
        textStartTime.setText(calendarStart == null? "":TimeUtils.getTimeByDate(calendarStart.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

    @OnClick(R.id.view_filter_2)
    void timeEndChoose() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (calendarEnd == null) {
                    calendarEnd = Calendar.getInstance();
                }
                calendarEnd.setTime(date);
                onTimeEndChoosed();
            }
        }).addOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .build();
        pvTime.show();
        ViewUtils.hideInput(mContext);
    }

    void onTimeEndChoosed() {
        textEndTime.setText(calendarEnd == null? "":TimeUtils.getTimeByDate(calendarEnd.getTime(), "yyyy-MM-dd"));
        if(calendarStart != null && calendarEnd != null){
            mRecyclerView.refresh();
        }else if(calendarStart == null && calendarEnd == null){
            mRecyclerView.refresh();
        }
    }

}
